﻿using _111.Models;
using Dapper;
using Microsoft.Extensions.Logging;
using MyDapperApi.Models;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using QYWXUpdate.DataModel;
using System.Data;
using System.Text;
using System.Text.Json.Nodes;

namespace MyDapperApi.Services;

public class NetCommonService : INetCommonService
{
    private readonly IConfiguration _configuration;
    private readonly IHttpClientFactory _httpClientFactory;

    // 通过依赖注入获取配置，从而读取连接字符串
    public NetCommonService(IHttpClientFactory httpClientFactory, IConfiguration configuration)
    {
        _configuration = configuration;
        _httpClientFactory = httpClientFactory;
    }

    /// <summary>
    /// 数据流转String
    /// </summary>
    /// <param name="stream"></param>
    /// <returns></returns>
    public async Task<string> StreamToStringAsync(Stream stream)
    {
        if (stream.CanSeek)
        {
            stream.Seek(0, SeekOrigin.Begin);
        }

        using (StreamReader reader = new StreamReader(stream))
        {
            return await reader.ReadToEndAsync();
        }
    }

    /// <summary>
    /// 获取企业微信token标准方法
    /// </summary>
    /// <param name="corpId"></param>
    /// <param name="secret"></param>
    /// <returns></returns>
    public async Task<CommonResponse> PostNetCommon(NetCommonRequest request)
    {
        var result = new CommonResponse();
        var client = _httpClientFactory.CreateClient();
        client.DefaultRequestHeaders.Add("ContentType", "application/json");

        var response = new HttpResponseMessage();

        if (request.Type == 0)
        {
            response = await client.GetAsync(request.Url);
        }
        else
        {
            var postContent = new StringContent(request.Body.ToString(), Encoding.UTF8, "application/json");
            response = await client.PostAsync(request.Url, postContent);
        }

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await StreamToStringAsync(responseStream);
                result.SetSuccess(res);
            }

        }
        else
            result.SetError("发送失败");

        return result;
    }

    public class NetCommonRequest
    {
        public string Url { get; set; }
        public JsonObject Body { get; set; }
        /// <summary>
        /// 0为get1为post
        /// </summary>
        public int Type { get; set; }
    }
}